
package com.kugou.game.sdk.ui.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Paint;
import android.os.IBinder;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils.TruncateAt;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kugou.game.sdk.ui.activity.CommonSdkActivity;
import com.kugou.game.sdk.ui.fragment.SecurityPsdResetFragment;
import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.utils.Rx;

/**
 * 描述:支付密码输入对话框
 *
 * @author wcj
 * @since 2015年12月8日 上午11:05:53
 */
public class InputPayPasswdDialog extends Dialog {

    /**
     * Interface definition for a callback to be invoked when the password
     * changed or is at the maximum length.
     */
    public interface OnPasswordChangedListener {

        /**
         * Invoked when the password changed.
         */
        public void onChanged(String psw);

        /**
         * Invoked when the password is at the maximum length.
         */
        public void onMaxLength(String psw);

    }

    private Activity mActivity;

    private TextView mGameInfo, mYoubiInfo, mErrorInfo, mGetBackPayPwd;

    private EditText mGridPasswordView;

    private LoadingView mLoadingView;

    private LinearLayout mContentLayout;

    private OnPasswordChangedListener mOnPasswordChangedListener;

    public InputPayPasswdDialog(Activity activity) {
        super(activity);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        this.mActivity = activity;

        setContentView(Rx.layout.kg_dialog_input_pay_passwd);

        setCanceledOnTouchOutside(false);

        setDialogDefaultSize();

        initView();
    }

    private void initView() {
        mGameInfo = (TextView) findViewById(Rx.id.kg_input_pay_pwd_game_info);
        mYoubiInfo = (TextView) findViewById(Rx.id.kg_input_pay_pwd_youbi_info);
        mErrorInfo = (TextView) findViewById(Rx.id.kg_input_pay_pwd_error_info);
        mErrorInfo.setSingleLine();
        mErrorInfo.setEllipsize(TruncateAt.END);
        mErrorInfo.setText("支付密码输入错误，请重新输入");
        mGetBackPayPwd = (TextView) findViewById(Rx.id.kg_get_back_pay_pwd);
        mGetBackPayPwd.setText("找回支付密码");
        // 设置下划线
        mGetBackPayPwd.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        // 设置抗锯齿
        mGetBackPayPwd.getPaint().setAntiAlias(true);
        mGetBackPayPwd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mActivity != null && !mActivity.isFinishing()) {
                    mActivity.startActivity(CommonSdkActivity.creatIntent(mActivity,
                            SecurityPsdResetFragment.class.getName(),
                            Rx.string.kg_reset_security_psd));
                    dismiss();
                }
            }
        });

        mGridPasswordView = (EditText) findViewById(Rx.id.kg_input_pay_pwd_gridpasswordview);
        mLoadingView = (LoadingView) findViewById(Rx.id.kg_loadingView);
        mContentLayout = (LinearLayout) findViewById(Rx.id.kg_dialog_content);

        mGridPasswordView.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                synchronized (this) {
                    String newStr = mGridPasswordView.getText().toString();
                    if (newStr.length() == 6) {
                        hideSoftInput();
                        showLoadingView();

                        mGridPasswordView.setText("");
                        mOnPasswordChangedListener.onMaxLength(newStr);
                    }
                }
            }
        });

        ImageView closeBtn = (ImageView) findViewById(Rx.id.kg_common_dialog_close_img);
        closeBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                hideSoftInput();
                dismiss();
            }
        });

    }

    public void hideSoftInput() {
        if (mGridPasswordView == null) {
            return;
        }

        try {
            IBinder token = mGridPasswordView.getWindowToken();
            ((InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(token, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setDialogDefaultSize() {
        Window dialogWindow = getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics dm = new DisplayMetrics();
        mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int parentWidth = dm.widthPixels;
        int parentHeight = dm.heightPixels;

        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;

        if (parentWidth < parentHeight) {// 竖屏
            lp.width = (int) (parentWidth * 0.9);
        } else {
            lp.width = (int) (parentHeight * 0.9);
        }
        dialogWindow.setAttributes(lp);
        dialogWindow.setGravity(Gravity.CENTER);
    }

    @Override
    public void onContentChanged() {
        super.onContentChanged();

        initView();
    }

    private void setErrorInfoVisibility(boolean visibility) {
        mErrorInfo.setVisibility(visibility ? View.VISIBLE : View.GONE);
        mGetBackPayPwd.setVisibility(visibility ? View.VISIBLE : View.GONE);
    }

    private void showLoadingView() {
        mLoadingView.setVisibility(View.VISIBLE);
        mContentLayout.setVisibility(View.INVISIBLE);
    }

    private void hideLoadingView() {
        mLoadingView.setVisibility(View.GONE);
        mContentLayout.setVisibility(View.VISIBLE);
    }

    /**
     * 设置游币数，游戏名字
     * 
     * @param gameName
     * @param youbiAccount
     */
    public void setPayInfo(String gameName, String youbiAccount) {
        mGameInfo.setText(Html
                .fromHtml("<font color=#666666>通过游币钱包向</font>" + "<font color=#fc5f28>" + gameName
                        + "</font>" + "<font color=#666666>游戏支付</font>"));
        mYoubiInfo.setText(Html.fromHtml("<font color=#666666>游币：</font>" + "<font color=#fc5f28>"
                + youbiAccount + "</font>" + "<font color=#666666>个</font>"));
    }

    /**
     * 设置密码输入框变化监听
     * 
     * @param listener
     */
    public void setOnPasswordChangedListener(OnPasswordChangedListener listener) {
        mOnPasswordChangedListener = listener;
    }

    /**
     * 支付密码失败处理
     */
    public void passwdError(String error) {
        setErrorInfoVisibility(true);
        hideLoadingView();
        mGridPasswordView.setText("");
        mErrorInfo.setText(error);
    }
}
